$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/jxlaboratory/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true },
            { label: '操作', name: 'id', index: 'id', width: 110,
                formatter: function (cellvalue, options, rowObject) {
                      var num=rowObject.num;
                      var text="<a class='btn btn-default' onclick='showDevice("+cellvalue+","+num+")' ><i class='fa fa-desktop' style='font-size: 10px'></i>&nbsp;管理</a>";
                      text=text+"&nbsp;&nbsp;&nbsp;<a class='btn btn-default' onclick='showManager("+cellvalue+")' ><i class='fa fa-pencil-square-o' style='font-size: 10px'></i>&nbsp;管理员</a>"
                    return text;

                },

            },
			{ label: '实验室名称', name: 'name', index: 'name', width: 80 },
            { label: '宣传图', name: 'imgUrl', index: 'img_url', width: 80 , formatter: function (cellvalue, options, rowObject) {
                    return "<img src="+cellvalue+" style='width: 120px; height: 60px' />";
                }},
            { label: '实验室简介', name: 'introduction', index: 'introduction', width: 80 },
			{ label: '实验室编号', name: 'num', index: 'num', width: 80 },
			{ label: '设备数量', name: 'deviceSize', index: 'device_size', width: 80 },
            { label: '公网ip', name: 'internetIp', index: 'internet_ip', width: 80 },
            { label: '学院', name: 'schoolName', index: 'school_id', width: 80 },
			{ label: '排序', name: 'orderNum', index: 'order_num', width: 80 }


        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        shrinkToFit:true,
        autoScroll: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	//$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "scroll" });
        }
    });


    Simditor.locale = 'zh-CN';
    toolbar = [ 'title', 'bold', 'italic', 'underline', 'strikethrough',
        'color', 'fontScale', 'ol', 'ul', 'blockquote', 'code', 'table',
        'link', 'image', 'hr',  'indent', 'outdent','alignment' ];

    editor = new Simditor({   // 富文本
        textarea: $('#editor'),
        placeholder: '这里输入文字...',
        toolbar: toolbar,
        pasteImage: true,
        defaultImage: '/simditor/images/image.png',
        upload: {
            url: baseURL + 'sys/oss//edit/upload',
            params: null,
            fileKey: "file",
            connectionCount: 1,
            leaveConfirm: "正在上传,确定要取消上传文件吗?"}

    });

    new AjaxUpload('#upload', {
        action: baseURL + "sys/oss/upload",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
                if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))){
                    alert('请上传正确的图片格式!');
                    return false;
                }
            layer.load('努力上传中', {
                shade: [0.3,'#fff'] //0.1透明度的白色背景
            });
        },
        onComplete : function(file, r){
            layer.closeAll('loading');
            if(r.code == 0){

                alert(r.url);
                vm.jxLaboratory.imgUrl=r.url;
                $("img").attr("src",r.url);

            }
        }
    });

});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};
var ztree;
var editor; // 富文本
var loading;  // 缓冲效果
var vm = new Vue({
	el:'#rrapp',
	data:{
        q:{
            name: null,
            num:null
        },
		showList: true,
		title: null,
		jxLaboratory: {schoolId:0},
        managerTitle:"",
        managerShow:false,
        showList1:false,
        jxLaboratoryManager:{},   // 管理员
        treeData: {},
        parentNames: {}, // 所有父级名称
        parentIds: {}, //  所有父级id
        treeMap:{} // 所有的树id-name
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
            vm.showList1=true;
			vm.title = "新增";
			vm.jxLaboratory = {"schoolName":"请选择"};
            vm.getDept();
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.showList1=true;
            vm.title = "修改";
            vm.getDept();
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
		    vm.jxLaboratory.laboratoryDesc=editor.getValue();
		    console.log((vm.jxLaboratory));
		    $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
                var url = vm.jxLaboratory.id == null ? "sys/jxlaboratory/save" : "sys/jxlaboratory/update";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: 'application/x-www-form-urlencoded',
                    dataType:'json',
                    data: vm.jxLaboratory,
                    success: function(r){
                        if(r.code === 0){
                             layer.msg("操作成功", {icon: 1});
                             vm.reload();
                             $('#btnSaveOrUpdate').button('reset');
                             $('#btnSaveOrUpdate').dequeue();
                        }else{
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }
                    }
                });
			});
		},
    saveOrUpdate1: function (event) {
		 var password=$("#password").val();
		 if(password!="******"){
             vm.jxLaboratoryManager.password=$("#password").val();
         }
        $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
            var url = vm.jxLaboratoryManager.id == null ? "sys/jxlaboratorymanager/save" : "sys/jxlaboratorymanager/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.jxLaboratoryManager),
                success: function(r){
                    if(r.code === 0){
                        layer.msg("操作成功", {icon: 1});
                        vm.reload();
                        $('#btnSaveOrUpdate').button('reset');
                        $('#btnSaveOrUpdate').dequeue();
                    }else{
                        layer.alert(r.msg);
                        $('#btnSaveOrUpdate').button('reset');
                        $('#btnSaveOrUpdate').dequeue();
                    }
                }
            });
        });
    },
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
               if(!lock) {
                    lock = true;
		            $.ajax({
                        type: "POST",
                        url: baseURL + "sys/jxlaboratory/delete",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
				    });
			    }
             }, function(){
             });
		},
		getInfo: function(id){
			$.get(baseURL + "sys/jxlaboratory/info/"+id, function(r){
                vm.jxLaboratory = r.jxLaboratory;
                $("img").attr("src",vm.jxLaboratory.imgUrl);
                vm.jxLaboratory.schoolName=vm.treeMap[r.jxLaboratory.schoolId];
                editor.setValue(vm.jxLaboratory.laboratoryDesc);
                console.log(vm.jxLaboratory);
            });
		},
		reload: function (event) {
			vm.showList = true;
			 vm.showList1=false;
            vm.managerShow=false;

			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'name': vm.q.name,'num':vm.q.num},
                page:page
            }).trigger("reloadGrid");
		},
        deptTree: function () {  //   选择部门
        layer.open({
            type: 1,
            offset: '50px',
            skin: 'layui-layer-molv',
            title: "选择部门",
            area: ['300px', '450px'],
            shade: 0,
            shadeClose: false,
            content: jQuery("#deptLayer"),
            btn: ['确定', '取消'],
            btn1: function (index) {
                var node = ztree.getSelectedNodes();
                console.log(node);
                if(node[0].level<1&&node[0].deptId==0){
                  layer.msg("请选择正确的学校",{icon:1});
                }else{
                    //选择上级部门
                    vm.jxLaboratory.schoolName =node[0].name;
                    vm.jxLaboratory.schoolId=node[0].deptId;
                    layer.close(index);
                }
            }
        });
    }, getDept: function () {
            //加载部门树
            $.get(baseURL + "sys/dept/select", function (r) {
                console.log(r);
                var first_deptId=r.deptList[0].deptId;   //  第一个id
                ztree = $.fn.zTree.init($("#deptTree"), setting, r.deptList);
                var node = ztree.getNodeByParam("deptId", 0);
                node=(node!=null?node:ztree.getNodeByParam("deptId", first_deptId));
                ztree.selectNode(node);
                vm.treeData = node;
                vm.getAllParent(vm.treeData);  //  得到所有的父级数据
                console.log(vm.parentNames);
                console.log(vm.parentIds);
                console.log(vm.treeMap);
                if(vm.jxLaboratory.schoolId!=undefined){
                    vm.jxLaboratory.schoolName=vm.treeMap[vm.jxLaboratory.schoolId];
                }
            })
        }, getAllParent: function (data) {  //  得到所有的父级数据
            vm.treeMap[data.deptId]=data.name;
            if(data.deptId!=0&&data.level==0){ //  学校
                vm.parentNames[data.deptId]="";
                vm.parentIds[data.deptId]=0;
            }
            var ch = data.children;
            console.log(ch.length)
            if (ch.length > 0) {
                ch.forEach(function (child) {
                    vm.treeMap[child.deptId]=child.name;
                    var pid = data.deptId; //  父级id
                    var pName = data.name; //  父级名称
                    var pPnames = vm.parentNames[pid]; // 父级上一级名称；
                    var pPIds = vm.parentIds[pid];//  父级的上以及id;
                    var dptId = child.deptId;  // 当前id
                    if(pPnames != undefined ){
                        vm.parentNames[dptId]=pPnames.length>0?pPnames + "|" + data.name:data.name;
                    }else{
                        vm.parentNames[dptId]=data.level>0?data.name:"";
                    }
                    if(pPIds != undefined){
                        vm.parentIds[dptId]=pPIds + "|" + data.deptId;
                    }else{
                        vm.parentIds[dptId]=data.level>0? data.deptId:"";
                    }
                    if (child.children!= undefined) {
                        vm.getAllParent(child);
                    }
                })

            }
        },getFirstText:function(text){
            var txts=text.split("|");
            return parseInt(txts[1]);
        }

    }

});




function showDevice(id,num){
    window.location.href="jxcomputydevice.html?id="+id+"&&num="+num;
   // window.location.href="computyDevices.html?id="+id+"&&num="+num;
}

function showManager(id){
    debugger;
    vm.managerShow=true;
    vm.showList = false;
    $.get(baseURL + "sys/jxlaboratorymanager/managerInfo/"+id, function(r){
        if(r.jxLaboratoryManager!=null){
            vm.managerTitle="编辑管理员"
            vm.jxLaboratoryManager = r.jxLaboratoryManager;
            $("#password").val("******");
        }else{
            vm.managerTitle="添加管理员"
            vm.jxLaboratoryManager={};
            vm.jxLaboratoryManager.laboratoryId=id;
            $("#password").val("");
        }
    });
}